package com.example.cachedesign.business.service;

import com.example.cachedesign.business.domain.Student;
import com.example.cachedesign.business.repo.StudentRepository;
import com.example.cachedesign.cache.ConcurrentMapCacheService;
import com.example.cachedesign.canal.RedisRepository;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Service;

@Service
public class StudentService implements BeanPostProcessor {
    private final StudentRepository studentRepository;
    private final ConcurrentMapCacheService concurrentMapCacheService;

    public StudentService(StudentRepository studentRepository, ConcurrentMapCacheService concurrentMapCacheService) {
        this.studentRepository = studentRepository;
        this.concurrentMapCacheService = concurrentMapCacheService;
    }

    public Student getStudent(Long id) {
        RedisRepository redisRepository = RedisRepository.singleton();
        final String key = "student:" + id;
        Student student = (Student) concurrentMapCacheService.get(key);
        if (student == null) {
            student = (Student) redisRepository.getObject(key);
            if (student == null) {
                student = studentRepository.findById(id).get();
                redisRepository.setObject(key, student);
            }
            concurrentMapCacheService.update(key, student);
        }
        return student;
    }

    public Boolean update(Student student) {
        studentRepository.saveAndFlush(student);
        return true;
    }
}
